import { wxRequest } from '../../utils/server.js';  
const _wxRequest = new wxRequest();
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: app.globalData.imgUrl,
    contentImgsnum:6,
    loading: false,
    isIphoneX: app.globalData.isIphoneX,
    coverImgs: [],
    extraNodes: [
      {
        type: "after",
        dragId: "plus",
        slot: "plus",
        fixed: true
      }
    ],
    pageMetaScrollTop: 0,
    scrollTop: 0, 
    contentImgs: [], //介绍图
    isOver: false,
    delayTime: 0,
    uploadUrl: wx.getStorageSync('uploadUrl'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id:options.id
    },()=>{
      this.getDetail()
    })
   
  },
 
  onShow: function () { 
    this.dragcontentImgs = this.selectComponent('#dragcontentImgs');
    this.dragcontentImgs.init();
  },


  getDetail:function(){
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/dyeRecord/getById/'+this.data.id,
      method: 'get',
      data:{} 
    }, (res) => { 
      this.setData({
        detail:res.vo,
        contentImgs:res.vo.dyeRecordImgs
      },()=>{
        this.dragcontentImgs.init();
      })
      console.log(res,'获取详情')
    })
  },



 



  contentSortEnd(e) {
    this.setData({
      contentImgs: e.detail.listData
    });
  },
  contentChange(e) {
    this.setData({
      contentImgs: e.detail.listData
    });
    this.dragcontentImgs.init()
  },
  contentSizeChange(e) {
    wx.pageScrollTo({ scrollTop: 0 })
    this.setData({
      size: e.detail.value
    });
    this.dragcontentImgs.init();
  },

  contentItemClick(e) {
    console.log(e);
  },
  contentToggleFixed(e) {
    let key = e.currentTarget.dataset.key;
    let { contentImgs } = this.data;
    contentImgs[key].fixed = !contentImgs[key].fixed
    this.setData({
      contentImgs: contentImgs
    });
    this.dragcontentImgs.init();
  },

  contentAdd(e) {
    let contentImgs = this.data.contentImgs;
    var that = this
    wx.chooseImage({
      count: that.data.contentImgsnum - that.data.coverImgs.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) { 
        var tempFilePaths = res.tempFilePaths;
        that.uploadFile(res.tempFilePaths, 'contentImgs')
      }
    });
  },

  //上传图片
  uploadFile: function (pics, idName) {
    var that = this
    var listData = this.data[idName]
    this.setData({
      loading: true
    })
    for (var i = 0; i < pics.length; i++) {
      (function (i) { 
        wx.uploadFile({
          url: app.globalData.apiUrl + '/gds/protected/comm/file/gds.GoodsImgVO/fileUpload',
          header: {
            "Authorization": wx.getStorageSync('Authorization'),
          },
          formData: {
            width: 750
          },
          filePath: pics[i],
          name: 'file',
          success: function (res) {
            if (typeof res.data == "string") {
              var resdata = JSON.parse(res.data)
            }
            if (resdata.success) {

              var item = {
                imgName: resdata.datas.vo.fileName,
                imgPath: resdata.datas.vo.relativeFilePath,
                fixed: false
              }
              listData.push(item)
              that.setData({
                [idName]: listData
              })

              //初始化组件
              if (idName == 'coverImgs') {
                that.dragcoverImgs.init();
              } else if (idName == 'contentImgs') {
                that.dragcontentImgs.init();
              }

              //最后一张关闭遮罩 
              console.log(i + 1 == pics.length, 'last')
              if (i + 1 == pics.length) {
                that.setData({
                  loading: false
                })
              }

            }
          },
          fail: function (res) { 
          }
        }) 
      })(i)
    }
  },
 
  scroll(e) {
    this.setData({
      pageMetaScrollTop: e.detail.scrollTop
    })
  },

  // 页面滚动
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },

  getUserInfo (e) {
    var url = '/gds/protected/dyeRecord/getCustByMobile';
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: { custMobile: e.detail.value }
    }, (res) => {
      console.log(res)
      if (res.vo != null) {
        this.setData({
          detail:res.vo,
          contentImgs:res.vo.dyeRecordImgs || []
        },()=>{
          this.dragcontentImgs.init();
        })
      } else {
        // this.data.detail.mobile = e.detail.value
        // this.data.detail.custName = ''
        // this.data.detail.note = ''
        this.setData({
          contentImgs: []
        },()=>{
          this.dragcontentImgs.init();
        })
      }
    })
  },
  
  //表单提交
  formSubmit: function(e) {
    var formdata = e.detail.value; 
    let cus = wx.getStorageSync('cusData')
    if (cus) {
      formdata.custName = cus.custName
      formdata.custMobile = cus.custMobile
      formdata.note = cus.note
      formdata.dyeRecordImgs = cus.dyeRecordImgs
    }
   
    if (formdata.custName == '') {
      wx.showToast({
        icon: 'none',
        title: '姓名不能为空',
      })
      return
    }
   
    if (formdata.custMobile == '') {
      wx.showToast({
        icon: 'none',
        title: '手机号不能为空',
      })
      return
    }
 
  

    if (formdata.dyeRecordImgs && formdata.dyeRecordImgs.length < 1) {
      wx.showToast({
        icon: 'none',
        title: '请上传效果图片',
      })
      return
    }

    formdata.dyeRecordImgs=this.data.contentImgs
     
    console.log(formdata,'formdata')
    let checkList = wx.getStorageSync('checkList')
    if (checkList) {
      this.data.delayTime = checkList.length * 810
      checkList.map((item, index) => {
          setTimeout(() => {
            formdata.id = item
            console.log('遍历了'+ index + '次， id是： ' + formdata.id ,item);
            _wxRequest.wxTonkenAjax({
              url: app.globalData.apiUrl + '/gds/protected/dyeRecord/getById/'+formdata.id,
              method: 'get',
              data:{} 
            }, (res) => { 
              console.log(res.vo);
              let subForm = {
                ...res.vo,
                custName: formdata.custName,
                custMobile: formdata.custMobile,
                note: formdata.note,
                dyeRecordImgs: formdata.dyeRecordImgs,
              }
              let cusData = {
                custName: formdata.custName,
                dyeRecordImgs: formdata.dyeRecordImgs,
                custMobile: formdata.custMobile,
                note: formdata.note
              }
              wx.setStorageSync('cusData', cusData)
              console.log('subForm', subForm);
              this.formRequest(subForm);
              console.log(res,'获取详情')
            })
            this.data.delayTime = 800 * index
          }, 800 * index);
        
      })
    } else {
      console.log(1111111111111111111111111111);
      formdata.id = this.data.id
      _wxRequest.wxTonkenAjax({
        url: app.globalData.apiUrl + '/gds/protected/dyeRecord/getById/'+formdata.id,
        method: 'get',
        data:{} 
      }, (res) => { 
        console.log(res.vo);
        let subForm = {
          ...res.vo,
          custName: formdata.custName,
          custMobile: formdata.custMobile,
          note: formdata.note,
          dyeRecordImgs: formdata.dyeRecordImgs,
        }
        let cusData = {
          custName: formdata.custName,
          dyeRecordImgs: formdata.dyeRecordImgs,
          custMobile: formdata.custMobile,
          note: formdata.note
        }
        wx.setStorageSync('cusData', cusData)
        this.formRequest(subForm);
        console.log(res,'获取详情')
      })
    }
    
  },




  //请求
  formRequest: function(formdata) {
    formdata.dyeRecordImgs.map((item, index) => {
      delete item.id
    })
    var url = '/gds/protected/dyeRecord/updateCustomer';
    var title = "保存成功"
   

    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: formdata
    }, (res) => {
      console.log(res)
      wx.showToast({
        title,
      })

      if(this.data.isOver) {
        return;
      }

      this.setData({
        isOver: true
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/color_recode/index',
        })
      }, this.data.delayTime)

    })
  },




  //再来一份
  copyHanlde:function(){
    this.setData({
      itemColor:{
        icon:this.data.detail.colorIcon,
        name:this.data.detail.colorName,
        id:this.data.detail.colorId,
        modeVal: this.data.detail.modeVal,
        operationJson: this.data.detail.operationJson,
        devId: this.data.detail.devId,
        colorName: this.data.detail.colorName
      }
    },()=>{
      wx.navigateTo({
        url: '/pages/colors_project/index',
      })
    })
    
  },
  
  onUnload: function () {
    wx.removeStorageSync('cusData')
    wx.removeStorageSync('checkList')
  },

  onHide: function () {
  },

 
})